//可以将路由的处理逻辑都放在这⾥,或根据需要写到与handler同级的单独⽂件
package http

import (
	"fmt"
	"gitee.com/legend9999/publisher/common"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/memstore"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os/exec"
	"path/filepath"
)

var (
	SessionKey  = "user"
	root        = gin.Default()
	bookGroup   *gin.RouterGroup
	userGroup   *gin.RouterGroup
	userHandler UserHandler
	bookHandler BookHandler
)

func initRouter() *gin.Engine {
	store := memstore.NewStore([]byte("secret"))
	root.Use(sessions.Sessions("mySession", store))

	templateFunc := initTemplateFunc()
	root.SetFuncMap(templateFunc)

	root.LoadHTMLGlob(common.GetRunPath() + "/views/**/*")
	root.Static("static", filepath.Join(common.GetRunPath(), "/static"))

	root.Any("/login", login)
	root.Any("/logout", logout)
	root.Any("/jd_reboot", reboot)

	// 稿件
	{
		bookGroup = root.Group("/book")
		bookGroup.Use(isLogin)
		bookGroup.GET("/list", bookHandler.bookList)
		bookGroup.Any("/create", bookHandler.create)
		bookGroup.Any("/finishStatus", bookHandler.finishStatus)
		bookGroup.Any("/startStatus", bookHandler.startStatus)
		bookGroup.Any("/edit", bookHandler.edit)
		bookGroup.Any("/del", bookHandler.del)
		bookGroup.Any("/detail", bookHandler.detail)
		bookGroup.Any("/all", bookHandler.all)
	}

	{
		userGroup = root.Group("/user")
		userGroup.Use(isLogin)
		userGroup.GET("/list", userHandler.list)
		userGroup.Any("/changePassword", userHandler.changePassword)
		userGroup.Any("/create", userHandler.create)

	}
	return root
}

func isLogin(c *gin.Context) {
	session := sessions.Default(c)
	user := session.Get(SessionKey)
	if user == nil {
		//c.Redirect(http.StatusCreated,"/login")
		c.Request.URL.Path = "/login"
		root.HandleContext(c)
		return
	}
	log.Printf("sess:%+v", session)
}

func reboot(c *gin.Context) {
	command := `/data/code/java/jd-customer-service/backstage.sh`
	cmd := exec.Command("/bin/sh", "-c", command)
	output, err := cmd.Output()
	if err != nil {
		c.JSON(http.StatusBadRequest, fmt.Sprintf("Execute Shell:%s failed with error:%s", command, err.Error()))
		return
	}
	c.JSON(http.StatusBadRequest, fmt.Sprintf("Execute Shell:%s finished with output:\n%s", command, string(output)))
}
